package com.weixin.paleituo.fragment;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.weixin.paleituo.R;
import com.weixin.paleituo.activity.ClassifyGoodsActivity;
import com.weixin.paleituo.activity.GoodsDetailsActivity;
import com.weixin.paleituo.activity.GoodsStoreActivity;
import com.weixin.paleituo.activity.LoginActivity;
import com.weixin.paleituo.activity.MyMessageActivity;
import com.weixin.paleituo.activity.SearchGoodsActivity;
import com.weixin.paleituo.activity.ShopCarActivity;
import com.weixin.paleituo.activity.WordofMouthActivity;
import com.weixin.paleituo.adapter.GoodsHomeAdapter;
import com.weixin.paleituo.adapter.HomeRecommandAdapter;
import com.weixin.paleituo.adapter.HotStoreHorizontalScrollViewAdapter;
import com.weixin.paleituo.adapter.MyGridViewAdapter;
import com.weixin.paleituo.adapter.MyViewPagerAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseFragment;
import com.weixin.paleituo.bean.ChosenAdsListBean;
import com.weixin.paleituo.bean.ClassesBean;
import com.weixin.paleituo.bean.GoodsShopHomeBean;
import com.weixin.paleituo.bean.HomeRecommandBean;
import com.weixin.paleituo.bean.ProductListBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.TheBannerBean;
import com.weixin.paleituo.bean.WordOfMouthStoreBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.SoldOutEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.HeaderAndFooterWrapper;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.MyHorizontalScrollView;
import com.weixin.paleituo.view.RecommandDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * Author yichao
 * Time  2018/3/15 9:50
 * Dest  商城首页
 */

public class GoodsHomeFragment extends BaseFragment {
    @BindView(R.id.iv_message_goodshome_fragment)
    ImageView mIvMessageGoodshomeFragment;
    @BindView(R.id.ll_headroot_fragment_goods_homefragment)
    LinearLayout mLlHeadrootFragmentGoodsHomefragment;
    @BindArray(R.array.goodsicoName)
    String[] proName;
    @BindView(R.id.recycle_fragment_goodshome)
    RecyclerView mRecycleFragmentGoodshome;
    private int[] iconResours = {R.mipmap.jiancai_icon, R.mipmap.jiaju_icon, R.mipmap.jiadian_icon,R.mipmap.ruanzhuang_icon};
    private int totalPage;//总的页数
    private int mPageSize = 8;//每页显示的最大数量
    private List<ProductListBean> listDatas;//总的数据源
    private List<View> viewPagerList;//GridView作为一个View对象添加到ViewPager集合中
    private MyGridViewAdapter mMyGridViewAdapterer;
    private ConvenientBanner mConvenientBanner;
    private ViewPager mViewPager;
    private View mHeadView;
    private View mFootView;
    private RecyclerView mRecyclerViewCommod;
    private List<ClassesBean> mClasses;
    private TextView mTvLookAllStore;
    private LoadingPagerHead mLoadingPagerHead;
    private RelativeLayout mRlLookAllStore;
    @BindView(R.id.iv_shop_car_fragment_goods_home)
    ImageView ivShopCar;
    private  List<HomeRecommandBean> homeRecommandBeansDataList=new ArrayList<>();
    private    List<ChosenAdsListBean> mChosenAdsListBeansList=new ArrayList<>();
    private HomeRecommandAdapter mHomeRecommandAdapter;
    private GoodsHomeAdapter mGoodsHomeAdapter;


    @Override
    public View initView(Context context) {


        mLoadingPagerHead = new LoadingPagerHead(mContext) {
            @Override
            protected void close() {

            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(mContext, R.layout.fragment_goods_homefragment);
            }

            @Override
            protected void reLoading() {
                retry();

            }
        };
       // return UIUtils.inflate(mContext, R.layout.fragment_goods_homefragment);
        // return ;
        return mLoadingPagerHead;
    }

    /**
     * 重新加载
     */
    private void retry() {
        Observable<StatusCode<GoodsShopHomeBean>> statusCodeObservable = ApiUtils.getApi().getHomeRecommand(BaseApplication.getUserId(), BaseApplication.getToken(), Contans.rows, 1).flatMap(new Function<StatusCode<List<HomeRecommandBean>>, ObservableSource<StatusCode<GoodsShopHomeBean>>>() {
            @Override
            public ObservableSource<StatusCode<GoodsShopHomeBean>> apply(StatusCode<List<HomeRecommandBean>> homeRecommandBeans) throws Exception {
                List<HomeRecommandBean> homeRecommandBeansData = homeRecommandBeans.getData();
                if (homeRecommandBeansData != null && homeRecommandBeansData.size() > 0) {

                    homeRecommandBeansDataList.clear();
                    homeRecommandBeansDataList.addAll(homeRecommandBeansData);

                   /* HomeRecommandAdapter homeRecommandAdapter = new HomeRecommandAdapter(mContext, homeRecommandBeansData);
                    mRecyclerViewCommod.setItemAnimator(new DefaultItemAnimator());
                    mRecyclerViewCommod.setLayoutManager(new GridLayoutManager(mContext, 2));
                    mRecyclerViewCommod.addItemDecoration(new RecommandDividerItemDecoration(mContext));
                    mRecyclerViewCommod.setAdapter(homeRecommandAdapter);*/
                }
                return ApiUtils.getApi().getgoodsShopHomeDate(Contans.defaultToken);
            }
        });
        HttpUtil.getInstance().toSubscribe(statusCodeObservable, new ProgressSubscriber<GoodsShopHomeBean>(mContext) {
            @Override
            protected void _onNext(StatusCode<GoodsShopHomeBean> goodsShopHomeBeanStatusCode) {
                mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                mHomeRecommandAdapter.notifyDataSetChanged();
                GoodsShopHomeBean data = goodsShopHomeBeanStatusCode.getData();


                if (goodsShopHomeBeanStatusCode.isFlag() && data != null) {
                    List<TheBannerBean> the_banner = data.getThe_banner();

                    if (the_banner != null && the_banner.size() > 0) {
                        //轮播图
                        mConvenientBanner.setPages(new CBViewHolderCreator<ImageViewHolder>() {
                            @Override
                            public ImageViewHolder createHolder() {
                                return new ImageViewHolder();
                            }
                        }, the_banner)
                                .setPageIndicator(new int[]{R.drawable.noselect_circle_shape, R.drawable.select_circle_shape}) //设置两个点作为指示器
                                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL); //设置指示器的方向水平  居中
                    }
                      /*店铺*/
                    final List<WordOfMouthStoreBean> wordOfMouthStoreList = data.getWordOfMouthStoreList();
                    if (wordOfMouthStoreList != null && wordOfMouthStoreList.size() > 0) {
                        MyHorizontalScrollView myHorizontalScrollView = mHeadView.findViewById(R.id.id_horizontalScrollView_layout_goodshome_head);

                        HotStoreHorizontalScrollViewAdapter hotStoreHorizontalScrollViewAdapter = new HotStoreHorizontalScrollViewAdapter(mContext, wordOfMouthStoreList);
                        myHorizontalScrollView.initDatas(hotStoreHorizontalScrollViewAdapter);
                        myHorizontalScrollView.setOnItemClickListener(new MyHorizontalScrollView.OnItemClickListener() {
                            @Override
                            public void onClick(View view, int pos) {
                                int storeId = wordOfMouthStoreList.get(pos).getStoreId();
                                GoodsStoreActivity.startActivity(mContext, storeId);
                            }
                        });
                    }
                    mClasses = data.getClasses();
                    List<ChosenAdsListBean> chosenAdsList = data.getChosenAdsList();
                    /**精选*/
                    if (chosenAdsList != null && chosenAdsList.size() > 0) {
                      /*  GoodsHomeAdapter goodsHomeAdapter = new GoodsHomeAdapter(mContext, chosenAdsList);
                        HeaderAndFooterWrapper headerAndFooterWrapper = new HeaderAndFooterWrapper(goodsHomeAdapter);
                        headerAndFooterWrapper.addHeaderView(mHeadView);
                        headerAndFooterWrapper.addFootView(mFootView);
                        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
                        mRecycleFragmentGoodshome.setLayoutManager(linearLayoutManager);
                        mRecycleFragmentGoodshome.setItemAnimator(new DefaultItemAnimator());
                        mRecycleFragmentGoodshome.setAdapter(headerAndFooterWrapper);*/

                        mChosenAdsListBeansList.clear();
                        mChosenAdsListBeansList.addAll(chosenAdsList);
                        mGoodsHomeAdapter.notifyDataSetChanged();
                    }
                } else {
                }

            }

            @Override
            protected void _onError(String message) {
                ToastUtils.makeText(message);
                mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);


            }
        }, "", lifecycleSubject, false, true);


        //首页推荐
/*        Observable<List<HomeRecommandBean>> homeRecommand = ApiUtils.getApi().getHomeRecommand(BaseApplication.getUserId(), BaseApplication.getToken(), Contans.rows, 1);
        HttpUtil.getInstance().toSubscribe(homeRecommand, new ProgressSubscriber<List<HomeRecommandBean>>(mContext) {
            @Override
            protected void _onNext(StatusCode<List<HomeRecommandBean>> listStatusCode) {
                List<HomeRecommandBean> dataRecommandBeans = listStatusCode.getData();
                if (listStatusCode.isFlag()&&dataRecommandBeans!=null &&dataRecommandBeans.size()>0){


                    HomeRecommandAdapter homeRecommandAdapter=new HomeRecommandAdapter(mContext,dataRecommandBeans);
                    mRecyclerViewCommod.setItemAnimator(new DefaultItemAnimator());
                    mRecyclerViewCommod.setLayoutManager(new GridLayoutManager(mContext,2));
                   mRecyclerViewCommod.setAdapter(homeRecommandAdapter);


                }else {
                    ToastUtils.makeText(listStatusCode.getDetailMsg());
                }

            }

            @Override
            protected void _onError(String message) {

                ToastUtils.makeText(message);

            }
        },"",lifecycleSubject,false,true);*/

    }

    //View mView = UIUtils.inflate(mContext, R.layout.fragment_goods_homefragment);


    @Override
    protected void initEvent() {
        super.initEvent();
        mRlLookAllStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WordofMouthActivity.startActivity(mContext);
            }
        });
        ivShopCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (BaseApplication.isLoginSuccess){
                    ShopCarActivity.startActivity(mContext);
                }else {
                    LoginActivity.startActivity(mContext,true);
                }
            }
        });


    }
    @Override
    protected void initData() {
        super.initData();
/*        if (Build.VERSION.SDK_INT >= 21) {
            mLlHeadrootFragmentGoodsHomefragment.setPadding(0, UIUtils.dip2px(20), 0, 0);
            mLlHeadrootFragmentGoodsHomefragment.setBackgroundColor(UIUtils.getColor(R.color.c_29ce7e));
        } else {
            mLlHeadrootFragmentGoodsHomefragment.setPadding(0, 0, 0, 0);
        }*/

        //  mRecycleFragmentGoodshome.setReFreshEnabled(false);
        EventBus.getDefault().register(this);
        mHeadView = UIUtils.inflate(mContext, R.layout.layout_goodeshome_head);
        mConvenientBanner = mHeadView.findViewById(R.id.id_cb_fragment_goodshome_fragment);
        mViewPager = mHeadView.findViewById(R.id.viewPager_goodshome_fragment);
        mTvLookAllStore = mHeadView.findViewById(R.id.tv_lookall_store_layout_goodshome_head);
        mRlLookAllStore = mHeadView.findViewById(R.id.rl_lookall_root_layout_coupons_singn);

        mFootView = UIUtils.inflate(mContext, R.layout.layout_goodeshome_footview);

        mRecyclerViewCommod = mFootView.findViewById(R.id.recyclerecommod_fragment_goodshome);

        listDatas = new ArrayList<>();
        for (int i = 0; i < proName.length; i++) {
            listDatas.add(new ProductListBean(proName[i], iconResours[i]));
        }
        LayoutInflater inflater = LayoutInflater.from(mContext);
        //总的页数，取整（这里有三种类型：Math.ceil(3.5)=4:向上取整，只要有小数都+1  Math.floor(3.5)=3：向下取整  Math.round(3.5)=4:四舍五入）
        totalPage = (int) Math.ceil(listDatas.size() * 1.0 / mPageSize);
        viewPagerList = new ArrayList<>();
        for (int i = 0; i < totalPage; i++) {
            //每个页面都是inflate出一个新实例
            GridView gridView = (GridView) inflater.inflate(R.layout.layout_gridview, mViewPager, false);
            gridView.setNumColumns(4);
            mMyGridViewAdapterer = new MyGridViewAdapter(mContext, listDatas, i, mPageSize);
            gridView.setAdapter(mMyGridViewAdapterer);
            mMyGridViewAdapterer.setOnItemOnclickListener(new MyGridViewAdapter.OnItemOnclickListener() {
                @Override
                public void onItemClick(Context context, int pos, View view) {
                    Log.i("TAG", "position的值为：" + pos + "-->pos的值为：" + pos);
                   // Toast.makeText(mContext, "你点击了 " + listDatas.get(pos).getProName(), Toast.LENGTH_SHORT).show();

                        switch (pos) {
                            case 0:
                            //建材
                                ClassifyGoodsActivity.startActivity(mContext, 3);
                                //新房
                                //   HouseHomeActivity.startActivity(context);
                                //      CollocationHouseActivity.startActivity(context);
                                //  FloorHomeActivity.startActivity(context);

                                break;
                            case 1:
                                //买房赠券
                                //   CollocationReleaseManagerActivity.startActivity(context);
                                //   ClassifyGoodsActivity.startActivity(mContext);

                                ClassifyGoodsActivity.startActivity(mContext, 0);
                                break;

                            case 2:
                                //家具家装
                                //   ClassifyGoodsActivity.startActivity(mContext);


                                ClassifyGoodsActivity.startActivity(mContext, 1);
                                break;
                            //家用电器
                            case 3:




                                ClassifyGoodsActivity.startActivity(mContext, 2);
                                break;
                        }


                }
            });
            //每一个GridView作为一个View对象添加到ViewPager集合中
            viewPagerList.add(gridView);
        }
        //设置ViewPager适配器
        mViewPager.setAdapter(new MyViewPagerAdapter(viewPagerList));

        mHomeRecommandAdapter = new HomeRecommandAdapter(mContext, homeRecommandBeansDataList);
        mRecyclerViewCommod.setItemAnimator(new DefaultItemAnimator());
        mRecyclerViewCommod.setLayoutManager(new GridLayoutManager(mContext, 2));
        mRecyclerViewCommod.addItemDecoration(new RecommandDividerItemDecoration(mContext));
        mRecyclerViewCommod.setAdapter(mHomeRecommandAdapter);


        mGoodsHomeAdapter = new GoodsHomeAdapter(mContext, mChosenAdsListBeansList);
        HeaderAndFooterWrapper headerAndFooterWrapper = new HeaderAndFooterWrapper(mGoodsHomeAdapter);
        headerAndFooterWrapper.addHeaderView(mHeadView);
        headerAndFooterWrapper.addFootView(mFootView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        mRecycleFragmentGoodshome.setLayoutManager(linearLayoutManager);
        mRecycleFragmentGoodshome.setItemAnimator(new DefaultItemAnimator());
        mRecycleFragmentGoodshome.setAdapter(headerAndFooterWrapper);
        retry();
    }

    @OnClick(R.id.iv_message_goodshome_fragment)
    public void onViewClicked() {
        if (BaseApplication.isLoginSuccess){

            MyMessageActivity.startActivity(mContext,BaseApplication.getUserId());

        }else {
            LoginActivity.startActivity(mContext,true);
        }
    }
    public class ImageViewHolder implements Holder<TheBannerBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, TheBannerBean data) {
            Glide.with(context).load(data.getImg()).into(imageView);
            // imageView.setImageResource(data);
            final int goodsid = data.getGoodsid();
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (goodsid!=0) {
                        GoodsDetailsActivity.startActivity(mContext, goodsid);
                    }
                }
            });
        }
    }

    @OnClick(R.id.rl_search_root_fragment_goods_homefragment)
    public void gotoSearch() {
        SearchGoodsActivity.startActivity(mContext);

    }

    @Override
    public void onResume() {
        super.onResume();
        mConvenientBanner.startTurning(2000);
    }
    @Override
    public void onPause() {
        super.onPause();

        mConvenientBanner.stopTurning();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void soldOutEvent(SoldOutEvent soldOutEvent){
        int mtype = soldOutEvent.getMtype();
        if (mtype==Contans.GOODS_SOLDOUT_TYPE||mtype==Contans.STORE_SOLDOUT_TYPE){
            mLoadingPagerHead.showPagerView(Contans.STATE_LOADING);
            retry();
        }


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
